package persistence.Impl;

import domain.Category;
import persistence.CategoryDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: petStore
 * @package: persistence
 * @className: CategoryDAOImpl
 * @author: suqianbei
 * @description: TODO
 * @date: 2021/10/30 19:55
 * @version: 1.0
 */
public class CategoryDAOImpl implements CategoryDAO {
    private static final String GET_CATEGORY_LIST="SELECT CATID AS categoryId,NAME,DESCN AS description FROM CATEGORY";
    private static final String GET_CATEGORY="SELECT CATID AS categoryId,NAME,DESCN AS description FROM CATEGORY WHERE CATID=?";
    @Override
    public List<Category> getCategoryList() {
        List<Category> categoryList=new ArrayList<Category>();
        try {
            Connection connection=DBUtil.getConnection();
            PreparedStatement preparedStatement=connection.prepareStatement(GET_CATEGORY_LIST);
            ResultSet resultSet=preparedStatement.executeQuery();
            while (resultSet.next())
            {
                Category category=new Category();
                category.setCategoryId(resultSet.getString(1));
                category.setName(resultSet.getString(2));
                category.setDescription(resultSet.getString(3));
                categoryList.add(category);
            }
            DBUtil.close(connection,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return categoryList;
    }

    @Override
    public Category getCategory(String CategoryId) {
           Category category=null;
        try {
            Connection connection=DBUtil.getConnection();
            PreparedStatement preparedStatement=connection.prepareStatement(GET_CATEGORY);
            preparedStatement.setString(1,CategoryId);
            ResultSet resultSet=preparedStatement.executeQuery();
            if (resultSet.next())
            {
                category=new Category();
                category.setCategoryId(resultSet.getString(1));
                category.setName(resultSet.getString(2));
                category.setDescription(resultSet.getString(3));
            }
            DBUtil.close(connection,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return category;
    }
}
